<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/comm.css">
    <link rel="stylesheet" href="css/main.css">
    <title>Chat</title>
</head>

<body>
    <div class="all" id="app">
        <div class="main">
            <!--leftmenu start-->
            <div class="leftmenu">
                <div class="userinfo">
                    <div class="userinfo_img">
                        <img v-bind:src="UserInfo.Logo" v-bind:alt="UserInfo.AccountID"></div>
                    <div class="userinfo_name">
                        <span>{{UserInfo.AccountName}}</span>
                    </div>
                </div>
                <div class="search">
                    <img src="imgs/search.png" alt="">
                    <input type="text" placeholder="搜索" v-model="key" />
                </div>
                <div class="tabpanle">
                    <div class="linkgroup" v-for="item in filterList">
                        <div class="groupName" @click.self='item.Open=!item.Open'>{{item.Gname}}({{item.AccountList.length}})</div>
                        <ul class='grouplist' v-for="item2 in item.AccountList" v-show="item.Open">
                            <li v-bind:data-account="item2.AccountID" @click='selectfriend'>
                                <img v-bind:src="item2.AccountLogo" v-bind:alt="item2.AccountID">
                                <span>{{item2.AccountName}}</span>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="setting">
                    <ul>
                        <li>
                            <img src="imgs/set.png" alt="setting">
                        </li>
                        <li>
                            <img src="imgs/Add.png" alt="Add">
                        </li>
                    </ul>
                </div>
            </div>
            <!--leftmenu end-->

            <!--rightcontent start-->
            <div class="right">
                <div class="righttitle">
                    <img class="titleimg" v-bind:src="selectedPerson.AccountLogo" v-show="selectedPerson.AccountLogo!=''" v-bind:alt="selectedPerson.AccountID">
                </div>

                <div class="content" id='rightmsgcontent'>
                    <div class="welcome">have fun !</div>
                </div>
                <!--chatwindows start-->
                <div class="chatwindows">
                    <div class="chattool">
                        <ul>
                            <li> <img src="imgs/Smile.png" alt="setting"></li>
                            <li> <img src="imgs/skip.png" alt="setting" @click='clearcache'></li>
                        </ul>
                    </div>
                    <div class="chattext">
                        <textarea name="" id="msgarea" cols="30" rows="8" v-model='sendmsg' class="msgarea" placeholder="在此处输入消息(Ctrl+Enter发送)" @keydown='send'></textarea>
                    </div>

                </div>
                <!--chatwindows end-->
            </div>
            <!--rightcontent end-->
        </div>
    </div>
    <input type="hidden" id="lastchatAccountid" v-model="selectedPerson.AccountID" />
</body>
<script src="js/vue.min.js"></script>
<script src="js/axios.min.js"></script>
<script>
    Date.prototype.Format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
                (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
    new Vue({
        el: "#app",
        data: {
            sendmsg: '',
            UserInfo: '',
            key: '',
            selectedPerson: {
                AccountID: '',
                AccountLogo: '',
                AccountName: ''
            },
            msgcache: {
                sendId: '',
                recvId: '',
                msglist: [{
                    msg: '',
                    time: '',
                    flag: '' //s=发送数据，r=接收数据
                }]
            },
            storagekey: ''
        },
        mounted: function () {
            this.getgrouplist();

        },
        computed: {
            filterList: function () {
                return this.searchlist();
            }
        },
        methods: {
            htmlEncode: function (str) {
                var div = document.createElement("div");
                div.appendChild(document.createTextNode(str));
                return div.innerHTML;
            },
            htmlDecode: function (str) {
                var div = document.createElement("div");
                div.innerHTML = str;
                return div.innerText;
            },
            searchlist: function () {
                let key = this.key;
                let orglist = this.UserInfo.Grouplist;
                if (key) {
                    let gplist = [];
                    for (let i = 0; i < orglist.length; i++) {
                        let gp = {};
                        gp.Open = true;
                        gp.Gname = orglist[i].Gname;
                        gp.AccountList = [];
                        for (let j = 0; j < orglist[i].AccountList.length; j++) {
                            if (orglist[i].AccountList[j].AccountName.toLowerCase().indexOf(key.toLowerCase()) !=
                                -1) {
                                gp.AccountList.push(orglist[i].AccountList[j]);
                            }
                        }
                        if (gp.AccountList.length > 0) {
                            gplist.push(gp);
                        }
                    }
                    return gplist;
                }
                return this.UserInfo.Grouplist;
            },
            getgrouplist: function () {
                let _this = this;
                axios.get('/getlist')
                    .then(function (response) {
                        _this.UserInfo = response.data;
                    });
            },
            rendermsg: function () {
                let strhtml = "",
                    mlist = (this.msgcache.msglist == null) ? [] : this.msgcache.msglist,
                    el_content = document.getElementById('rightmsgcontent');

                for (var i = 0; i < mlist.length; i++) {
                    if (mlist[i].flag === 's') {
                        strhtml += '<div class="msgright"><div class="content_text fl"><p>' + mlist[i].msg +
                            '</p></div><div class="fr"><img src="' + this.UserInfo.Logo +
                            '" alt="send"></div></div>';
                    } else {
                        strhtml += ' <div class="msgleft" ><div class="fl"><img src="' + this.selectedPerson
                            .AccountLogo + '" alt="recv"></div><div class="content_text fr"><p>' + mlist[i]
                            .msg + '</p></div></div>';
                    }
                    strhtml += '<div class="msgtime"><i>' + mlist[i].time + '</i></div>';
                }
                el_content.innerHTML = strhtml;
                el_content.scrollTop = el_content.scrollHeight;


            },
            selectfriend: function (e) {
                let storge = window.localStorage,
                    curaccountid = e.currentTarget.dataset.account;
                if (curaccountid != this.selectedPerson.AccountID) {
                    this.selectedPerson.AccountID = curaccountid;
                    this.storagekey = this.UserInfo.AccountID + '_' + this.selectedPerson.AccountID;
                    let curacc_lastMsginfo = storge.getItem(this.storagekey);
                    this.msgcache.sendId = this.UserInfo.AccountID;
                    this.msgcache.recvId = curaccountid;
                    this.msgcache.msglist = (JSON.parse(curacc_lastMsginfo) == null) ? [] : JSON.parse(
                        curacc_lastMsginfo);

                    this.selectedPerson.AccountLogo = e.currentTarget.querySelector('img').src;
                    let lis = document.querySelectorAll('.linkgroup li');
                    for (var index = 0; index < lis.length; index++) {
                        lis[index].classList.remove('libgcolor');
                    }
                    e.currentTarget.classList.add('libgcolor');

                    this.rendermsg();
                }
            },
            clearcache: function () {
                let storage = window.localStorage;
                storage.removeItem(this.storagekey);
                this.msgcache.msglist = [];
                this.rendermsg();
            },
            send: function (oEvent) {
                if (oEvent.keyCode == 13 && oEvent.ctrlKey) {
                    let _this = this,
                        _msg = _this.htmlEncode(oEvent.currentTarget.value),
                        _time = new Date().Format("yyyy-MM-dd hh:mm:ss");

                    //todo 发送到后台处理  
                    axios.post('/send', {
                            sendmsg: _msg,
                            sender: 10000,
                            recv: 10001
                        })
                        .then(function (response) {
                            let storge = window.localStorage,
                                storagemsg = storge.getItem(_this.storagekey),
                                cursendmsg = {
                                    msg: _msg,
                                    time: _time,
                                    flag: 's'
                                },
                                currecvmsg = {
                                    msg: response.data.msg,
                                    time: _time,
                                    flag: 'r'
                                },
                                lastmsginfo = JSON.parse(storagemsg) == null ? [] : JSON.parse(
                                    storagemsg);

                            lastmsginfo.push(cursendmsg);
                            lastmsginfo.push(currecvmsg);
                            storge.setItem(_this.storagekey, JSON.stringify(lastmsginfo));
                            _this.msgcache.msglist = lastmsginfo;
                            _this.rendermsg();
                            _this.sendmsg = '';

                        });
                }
            }
        }
    });
</script>

</html>